import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
function error(msg, type = 'error', time = 2000) {
  Message({
    message: msg,
    type: type,
    duration: time
  })
}
let loading = null
function startLoading(config) {
  try {
    if (config.headers.loading) {
      loading = Loading.service({
        lock: true,
        text: '请等待...',
        background: 'rgba(255,255,255,0)',
      })
      setTimeout(() => {
        if (loading) {
          loading.close()
        }
      }, 3000)
    }
  } catch (e) {
    console.log(e)
  }
}
function endLoading() {
  if (loading) {
    loading.close()
  }
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    startLoading(config)
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    endLoading()
    const res = response.data
    if (res.code === 200) {
      return res
    } else {
      error(res.msg || '系统繁忙')
      return Promise.reject()
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
